<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Auth,DB,View,App;
use App\Articles;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = $this->getArticles($this->getUserPermNum());
        return view('home')->with(['articles' => $articles]);
    }

    public function updateProfile(Request $request)
    {
        if ($request->user()) {
            // $request->user() 返回认证用户实例...
            var_dump($request->user());
        }
    }

    public function getUserPermNum()
    {
        if(!is_null(Auth::user())){
            return Auth::user()->perm_num;
        }else{
            return 1;
        }
    }

    public function getArticles($perm = 0)
    {
        $articles = Articles::where('perm_num','<=',$perm)->orderBy('id', 'desc')->paginate(5);
        return $articles;
    }

    public function getArticle(Request $request)
    {
        $aId = $request->input('id');
        if(is_null($aId)){
            echo "没有指定内容";die;
        }

        $article = Articles::where('id', '=', $aId)->first();
        $user = DB::select('select name,img from users where id = ?',[$article->auther]);

        $_comments = DB::table('comments')->where('a_id',$aId)->orderBy('updated_at', 'desc')->get();
        $comments = [];
        $comments_user = [];

        if($_comments){
            $comments = $_comments;
            foreach($comments as $k => $v){
                $u = DB::table('users')->where('id', $v->u_id)->first();
                $comments_user[$v->id]['name'] = $u->name;
                $comments_user[$v->id]['img'] = $u->img;
            }
        }

        if($this->getUserPermNum() >= $article->perm_num){
            return view('article.article')->with(['article' => $article, 'user' => $user[0], 'comments' => $comments, 'comments_user' => $comments_user]);
        }

        echo "无权访问此内容";die;
    }
}
